<template>
  <div id="home" class="wrapper">
    <!--    导航栏-->
    <nav-bar class="home-nav"><div slot="center">购物街</div></nav-bar>
    <!--    复用tab-control-->
    <tab-control
      :titles="['流行', '新款', '精选']"
      @tabClick="tabClick"
      ref="tabControl1"
      class="tab-control"
      v-show="isTabFixed"
    ></tab-control>
    <!--    使用batter-scroll-->
    <scroll
      class="content"
      ref="scroll"
      :probe-type="3"
      :pull-up-load="true"
      @scroll="contentScroll"
      @pullingUp="loadMore"
    >
      <!--    轮播图-->
      <home-swiper :banners="banners"></home-swiper>
      <!--    推荐信息-->
      <recommend-view :recommends="recommends"></recommend-view>
      <!--    本周流行-->
      <feature-view></feature-view>
      <!--    板块控制（流行，新款，精选）-->
      <tab-control
        :titles="['流行', '新款', '精选']"
        @tabClick="tabClick"
        ref="tabControl2"
      ></tab-control>
      <!--    商品列表-->
      <goods-list :goods="showGoods"></goods-list>
    </scroll>
    <!--    右下角一键返回，.native监听组件根元素的原生事件-->
    <back-top @click.native="backClick" v-show="isShowBackTop"></back-top>
  </div>
</template>

<script>
// 导入的是子组件
import HomeSwiper from "./childComps/HomeSwiper";
import RecommendView from "./childComps/RecommendView";
import FeatureView from "./childComps/FeatureView";

// 导入的是公共组件
import NavBar from "components/common/navbar/NavBar";
import TabControl from "components/content/tabControl/TabControl";
import GoodsList from "components/content/goods/GoodsList";
import Scroll from "components/common/scroll/Scroll";
import BackTop from "components/content/backTop/BackTop";

// 导入的是方法
import { getHomeMultidata, getHomeGoods } from "network/home";
import { debounce } from "common/utils";
import { itemListenerMixin } from "@/common/mixin";

export default {
  name: "Home",
  components: {
    NavBar,
    HomeSwiper,
    RecommendView,
    FeatureView,
    TabControl,
    GoodsList,
    Scroll,
    BackTop
  },
  mixins: [itemListenerMixin],
  data() {
    return {
      banners: [],
      recommends: [],
      goods: {
        pop: { page: 0, list: [] },
        new: { page: 0, list: [] },
        sell: { page: 0, list: [] }
      },
      currentType: "pop",
      isShowBackTop: false,
      isTabFixed: false,
      tabOffsetTop: 545,
      saveY: 0
    };
  },
  computed: {
    showGoods() {
      return this.goods[this.currentType].list;
    }
  },
  // destroyed() {
  //   console.log('home destroyed');
  // },
  // 页面进来时
  activated() {
    // console.log('activated');
    //scrollTo参数为X坐标，y坐标，延迟时间
    this.$refs.scroll.refresh();
    this.$refs.scroll.scrollTo(0, this.saveY, 0);
  },
  // 页面离开时
  deactivated() {
    // console.log("deactivated");
    // 1.保存y值
    this.saveY = this.$refs.scroll.scroll.y;
    // console.log(this.saveY);
    // 2.取消事件监听，事件、函数名
    this.$bus.$off("itemImageLoad", this.itemImgListener);
  },
  created() {
    // 1.请求多个数据
    this.getHomeMultidata();
    // 2.请求商品数据
    this.getHomeGoods("pop");
    this.getHomeGoods("new");
    this.getHomeGoods("sell");
  },
  mounted() {
    //这个地方img标签确实被挂载，但是其中的图片还没有占据高度
    // 1.图片加载完的事件监听,进行防抖操作
    // const refresh = debounce(this.$refs.scroll.refresh,200)
    // // 对监听的事件进行保存
    // this.itemImgListener = () => {
    //   refresh()
    // }
    // //监听item中图片加载完成
    // this.$bus.$on('itemImageLoad',this.itemImgListener )
    // this.$refs.scroll.scroll.refresh()
    // console.log('-----');
    // 2.获取tabControl的offsetTop
    // 所有的组件都有一个元素，用于获取组件的el
    // this.tabOffsetTop = this.$refs.tabControl
  },
  methods: {
    /**
     * 事件监听相关的方法
     */
    // 防抖动函数,减少刷新次数
    // debounce(func,delay){
    //   let timer = null
    //   return function (...args){
    //     if (timer) clearTimeout(timer)
    //     timer = setTimeout(() =>{
    //       func.apply(this,args)
    //     },delay)
    //   }
    // },
    tabClick(index) {
      switch (index) {
        case 0:
          this.currentType = "pop";
          break;
        case 1:
          this.currentType = "new";
          break;
        case 2:
          this.currentType = "sell";
          break;
      }
      // 让两个TabControl的currentIndex保持一致
      this.$refs.tabControl1.currentIndex = index;
      this.$refs.tabControl2.currentIndex = index;
    },
    //点击返回顶部
    backClick() {
      this.$refs.scroll.scrollTo(0, 0);
    },
    // 定义小图标显示位置
    contentScroll(position) {
      // 1.判断BackTop小图标是否显示
      this.isShowBackTop = -position.y > 1000;
      // console.log(position);

      // 2.决定tabControl是否吸顶（position:fixed）  tabOffsetTop默认为545
      this.isTabFixed = -position.y > this.tabOffsetTop;
    },
    // 上拉加载更多
    loadMore() {
      this.getHomeGoods(this.currentType);
      this.$refs.scroll.refresh();
    },
    swiperImageLoad() {
      this.tabOffsetTop = this.$refs.tabControl2.$el.offsetTop;
    },
    /**
     * 网络请求相关的方法
     */
    // 1.请求多个数据
    getHomeMultidata() {
      getHomeMultidata().then(res => {
        // this.result = res;
        this.banners = res.data.banner.list;
        this.recommends = res.data.recommend.list;
      });
    },
    getHomeGoods(type) {
      const page = this.goods[type].page + 1;
      getHomeGoods(type, page).then(res => {
        this.goods[type].list.push(...res.data.list);
        this.goods[type].page += 1;
        // 如需继续加载，则调用finishPullUp，下式方法可在Scroll组件方法中封装好
        this.$refs.scroll.finishPullUp();
      });
    }
  }
};
</script>

<style scoped>
#home {
  /*缺少此样式则轮播图会被遮盖*/
  /*padding-top: 44px;*/
  /*吸顶效果，要显示出来必须得把#home里的height和position样式注释掉*/
  /*vh=viewport height*/
  height: 100vh;
  position: relative;
}

.home-nav {
  background-color: var(--color-tint);
  color: #fff;
  /*在使用浏览器原生滚动时，为了让导航不跟随一起滚动*/
  /*position: fixed;*/
  /*left: 0;*/
  /*right: 0;*/
  /*top: 0;*/
  /*z-index: 9;*/
}
/*吸顶效果，要显示出来必须得把#home里的height和position样式注释掉*/
/*.tab-control {*/
/*  !*吸顶效果*!*/
/*  !*position: sticky;*!*/
/*  top: 44px;*/
/*  !*设置元素的堆叠顺序，拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面*/
/*  避免被下面的元素覆盖*!*/
/*  z-index: 9;*/
/*}*/

.content {
  overflow: hidden;
  position: absolute;
  top: 44px;
  bottom: 49px;
  left: 0;
  right: 0;
}
/*.content {*/
/*height: calc(100% - 93px);*/
/*overflow: hidden;*/
/*margin-top: 44px;*/
/*}*/

/*复用tab-control出现在购物街下面*/
.tab-control {
  /*使用相对定位才会出现在轮播图上面*/
  position: relative;
  /*z-index只对定位元素起效果*/
  z-index: 9;
}
</style>
